/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Xiaobao Zeng<zengxiaobao@skyworth.com>
 * Created Time: 2017-07-10 10:05:16
 * Last Modified: 2017-07-12 15:45:37
 * File Name: qkstatis.go
 * Description:
 */

package qkstatis

import (
	"crypto/tls"
	"fmt"
	"strings"
	"time"

	"qkleague/auth"

	"github.com/astaxie/beego/httplib"
	log "github.com/cihub/seelog"
)

//只有日数据和月数据 type=1（日数据） type=3（月数据）
//客户端上传的数据， 日数据-长度21(2017-01-01~2017-02-02)， 月数据-长度-15(2017-01~2017-02)
func LeagueProfitList(leagueId, timeRange string) (bool, interface{}) {
	timeType, shortTimeRange := timeTranfer(timeRange)
	if timeType == 0 {
		log.Errorf("rpc LeagueProfitList err. 无效的日期标识. timeType:%d", timeType)
		return false, nil
	}
	param := map[string]interface{}{
		"appkey":     QKSTATIS_APPKEY,
		"league_id":  leagueId,
		"type":       timeType,
		"time_range": shortTimeRange,
		"time":       time.Now().Unix(),
		"source":     2,
	}
	param["sign"] = auth.GetURLSignService().CalcURLSignByMap(param, QKSTATIS_SECRET_KEY)

	reqURL := fmt.Sprintf("https://%s/statis/lr-profit/list?appkey=%v&time=%v&type=%v&league_id=%v&washroom_id=0000&time_range=%v&source=%d&sign=%v", qkstatisHost, param["appkey"], param["time"], param["type"], param["league_id"], param["time_range"], param["source"], param["sign"])

	b := httplib.Post(reqURL)
	b.SetHost(qkstatisHost)
	b.JSONBody(map[string]interface{}{})
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	resp := make(map[string]interface{})
	if err := b.ToJSON(&resp); err != nil {
		log.Errorf("LeagueProfitList, rpc qkstatis err. 服务未找到")
		return false, nil
	}
	if int(resp["code"].(float64)) != 0 {
		log.Errorf("LeagueProfitList, rpc qkstatis err. 业务错误。code:%v, msg:%s", resp["code"], resp["msg"])
		return false, nil
	}
	return true, resp["data"]
}

func WashRoomProfitList(leagueId, washRoomId, timeRange string) (bool, interface{}) {
	timeType, shortTimeRange := timeTranfer(timeRange)
	if timeType == 0 {
		log.Errorf("rpc WashRoomProfitList err. 无效的日期标识. timeType:%d", timeType)
		return false, nil
	}
	param := map[string]interface{}{
		"appkey":      QKSTATIS_APPKEY,
		"league_id":   leagueId,
		"type":        timeType,
		"time_range":  shortTimeRange,
		"washroom_id": washRoomId,
		"time":        time.Now().Unix(),
		"source":      2,
	}
	param["sign"] = auth.GetURLSignService().CalcURLSignByMap(param, QKSTATIS_SECRET_KEY)

	reqURL := fmt.Sprintf("https://%s/statis/lr-profit/list?appkey=%v&time=%v&type=%v&league_id=%v&washroom_id=%s&time_range=%v&source=%d&sign=%v", qkstatisHost, param["appkey"], param["time"], param["type"], param["league_id"], param["washroom_id"], param["time_range"], param["source"], param["sign"])

	b := httplib.Post(reqURL)
	b.SetHost(qkstatisHost)
	b.JSONBody(map[string]interface{}{})
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	resp := make(map[string]interface{})
	if err := b.ToJSON(&resp); err != nil {
		log.Errorf("WashRoomProfitList, rpc qkstatis err. 服务未找到")
		return false, nil
	}
	if int(resp["code"].(float64)) != 0 {
		log.Errorf("WashRoomProfitList, rpc qkstatis err. 业务错误。code:%v, msg:%s", resp["code"], resp["msg"])
		return false, nil
	}
	return true, resp["data"]
}

func WasherProfitList(washerId, timeRange string) (bool, interface{}) {
	timeType, shortTimeRange := timeTranfer(timeRange)
	if timeType == 0 {
		log.Errorf("rpc WasherProfitList err. 无效的日期标识. timeType:%d", timeType)
		return false, nil
	}
	param := map[string]interface{}{
		"appkey":     QKSTATIS_APPKEY,
		"washer_id":  washerId,
		"type":       timeType,
		"time_range": shortTimeRange,
		"time":       time.Now().Unix(),
		"source":     2,
	}
	param["sign"] = auth.GetURLSignService().CalcURLSignByMap(param, QKSTATIS_SECRET_KEY)

	reqURL := fmt.Sprintf("https://%s/statis/washer-profit/list?appkey=%v&time=%v&type=%v&washer_id=%v&time_range=%v&source=%d&sign=%v", qkstatisHost, param["appkey"], param["time"], param["type"], param["washer_id"], param["time_range"], param["source"], param["sign"])

	b := httplib.Post(reqURL)
	b.SetHost(qkstatisHost)
	b.JSONBody(map[string]interface{}{})
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	resp := make(map[string]interface{})
	if err := b.ToJSON(&resp); err != nil {
		log.Errorf("WasherProfitList, rpc qkstatis err. 服务未找到")
		return false, nil
	}
	if int(resp["code"].(float64)) != 0 {
		log.Errorf("WasherProfitList, rpc qkstatis err. 业务错误。code:%v, msg:%s", resp["code"], resp["msg"])
		return false, nil
	}
	return true, resp["data"]
}

//需要的目标格式
//(2017-01-01~2017-02-02) -> (170101~170202)
//(2017-01~2017-02) -> (1701~1702)
//如果timeType=0， 则参数错误
func timeTranfer(timeRange string) (int, string) {
	newTimeRange := []byte(strings.Replace(timeRange, "-", "", -1)) //20170101
	timeLength := len(newTimeRange)
	timeType := 0
	if timeLength == 17 {
		timeType = 1
		tmp := make([]byte, 0, 13)
		tmp = append(tmp, newTimeRange[2:9]...)
		tmp = append(tmp, newTimeRange[11:]...)
		return timeType, string(tmp)
	} else if timeLength == 13 {
		timeType = 3
		tmp := make([]byte, 0, 9)
		tmp = append(tmp, newTimeRange[2:7]...)
		tmp = append(tmp, newTimeRange[9:]...)
		return timeType, string(tmp)
	}
	return timeType, ""
}
